import { ICondition } from '../../interfaces';
import send_msg from './_service';

interface IDocDataStore {
	docDataStore: {
		[table_name: string]: {
			summary: { totalRow: number, totalPage: number },
			conditionCurrent: Array<{ [field_name: string]: any }>,
			paramCurrent: { [field_name: string]: any },
			pagingCurrent: { size: number, index: number },
			currentTimeMillis: { simpleDate: string, timeStamp: number },
			dataArray: Array<{ [field_name: string]: any }>
		}
	};
}

class Model {

	private data: IDocDataStore;

	constructor(private table_name: string, private params: any) {
		this.init();
	}

	/*
	 * 执行查询
	 */
	public async query() {
		const data = await send_msg<IDocDataStore>('dataservice.findbusidata', this.params, false, false);
		this.data = data;
		return this;
	}

	/*
	 * 获取总行数
	 */
	public total_row() {
		return this.data.docDataStore[this.table_name].summary.totalRow;
	}

	/*
	 * 获取总页数
	 */
	public total_page() {
		return this.data.docDataStore[this.table_name].summary.totalPage;
	}

	/*
	 * 获取每页显示数据条数
	 */
	public paging_size() {
		return this.data.docDataStore[this.table_name].pagingCurrent.size;
	}

	/*
	 * 获取当前页码
	 */
	public paging_index() {
		return this.data.docDataStore[this.table_name].pagingCurrent.index;
	}

	/*
	 * 获取执行服务时间
	 */
	public time_str() {
		return this.data.docDataStore[this.table_name].currentTimeMillis.simpleDate;
	}

	/*
	 * 获取执行服务时间戳
	 */
	public time_number() {
		return this.data.docDataStore[this.table_name].currentTimeMillis.timeStamp;
	}

	/*
	 * 获取一级表数据
	 */
	public first_data() {
		return this.data.docDataStore[this.table_name].dataArray;
	}

	private init() {
	}
}

/*
 * 根据模型获取数据
 * @param actionid 系统参数actionid,fd.data.actionid
 * @param sessionid 系统参数sessionid,fd.data.sessionid
 * @param spaceid 项目spaceid
 * @param systemid 项目systemid
 * @param refsystemid 项目refsystemid
 * @param modelid 模型
 * @param table_name 表名，一级表名
 * @param condition 参数[可选参数],参数格式为{paging: {index: 1,size: 12},param: {},sort: {}}
 */
export default function get_model_data(_actionid: string, _sessionid: string, spaceid: string, systemid: string, refsystemid: string, modelid: string, table_name: string, condition?: ICondition) {
	const param = {
		condition: condition || {
			paging: {
				index: 1,
				size: 12
			},
			param: {},
			sort: {}
		},
		emptydataflag: 0,
		modelid,
		refsystemid,
		spaceid,
		systemid
	};
	return new Model(table_name, param);
}
